package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"time"
	"xinhua_bookstore/cache"
	"xinhua_bookstore/models"
	"xinhua_bookstore/pkg"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Register() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户名或密码错误",
		}
		c.ServeJSON()
		return
	}
	var u models.User
	u.Username = username
	u.Password = pkg.Md5(password)
	err := u.Creat()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "注册失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "注册成功",
	}
	c.ServeJSON()
	return
}
func (c *UserController) Login() {
	var err error
	username := c.GetString("username")
	password := c.GetString("password")
	key := "longin_file_" + username
	count, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if count >= 2 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "账号已被锁定",
		}
		c.ServeJSON()
		return
	}
	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户名或密码错误",
		}
		c.ServeJSON()
		return
	}
	var users models.User
	err = users.GetInitByUsername(username)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "登录失败",
		}
		c.ServeJSON()
		return
	}
	if users.ID == 0 {
		cache.Rdb.Incr(cache.Ctx, key)
		if count == 2 {
			cache.Rdb.Expire(cache.Ctx, key, time.Hour*2)
		}
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户名不存在",
		}
		c.ServeJSON()
		return
	}
	if users.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, key)
		if count == 2 {
			cache.Rdb.Expire(cache.Ctx, key, time.Hour*2)
		}
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "密码错误",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "登录成功",
	}
	c.ServeJSON()
	return
}
